package com.difsonapps.android.marker.activities;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonObjectRequest;
import com.difsonapps.android.marker.FeedActivity;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.adapters.AlbumGridAdapter;
import com.difsonapps.android.marker.adapters.FeedListAdapter;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Album;
import com.difsonapps.android.marker.beans.FeedItem;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;

public class AlbumsActivity extends Activity {
    private static final String TAG = AlbumsActivity.class.getSimpleName();
    private ListView gridView;
    private AlbumGridAdapter gridAdapter;
    private List<Album> albums;
    private String URL_ALBUM = "http://10.0.2.2/putmark/public/home/albums";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_albums);
		
		gridView = (ListView) findViewById(R.id.gridListAlbum);
		 
        albums = new ArrayList<Album>();
 
        gridAdapter = new AlbumGridAdapter(this, albums);
        gridView.setAdapter(gridAdapter);
        
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_ALBUM);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonAlbums(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
 
        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
            		URL_ALBUM, null, new Response.Listener<JSONObject>() {
 
                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                                parseJsonAlbums(response);
                            }
                        }
                    }, new Response.ErrorListener() {
 
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });
 
            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }
	}
        
        private void parseJsonAlbums(JSONObject response) {
        	//toast("Response : "+response.toString());
            try {
                JSONArray feedArray = response.getJSONArray("albums");
     
                for (int i = 0; i < feedArray.length(); i++) {
                	//toast("Loading item "+i);
                    JSONObject feedObj = (JSONObject) feedArray.get(i);
                    Album item = Album.parseFromJsonObject(feedObj);
                    /*Album item = new Album();
                    item.setId(feedObj.getInt("id"));
                    item.setName(feedObj.getString("name"));
     
                    // Image might be null sometimes
                    String image = feedObj.isNull("image") ? null : feedObj
                            .getString("image");
                    item.setImage(image);
                    item.setNbPicts(feedObj.getInt("nbPicts"));
                    item.setDesc(feedObj.getString("desc"));
                    item.setTimeStamp(feedObj.getString("timeStamp")); */    
                    
                    //toast("Loaded : "+item.getName());
                    albums.add(item);
                }
     
                // notify data changes to list adapater
                gridAdapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        private void toast(String text){
    		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.albums, menu);
		return true;
	}

}
